package com.dzm.demo.myshop.web.admin.service.impl;

import com.dzm.demo.myshop.commons.dto.BaseResult;
import com.dzm.demo.myshop.commons.dto.PageInfo;
import com.dzm.demo.myshop.commons.utils.RegexpUtils;
import com.dzm.demo.myshop.commons.validator.BeanValidator;
import com.dzm.demo.myshop.domain.TbUser;
import com.dzm.demo.myshop.web.admin.abstracts.AbstractsBaseServiceImpl;
import com.dzm.demo.myshop.web.admin.dao.TbUserDao;
import com.dzm.demo.myshop.web.admin.service.TbUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true)
public class TbUserServiceImpl extends AbstractsBaseServiceImpl<TbUser,TbUserDao> implements TbUserService {

    @Override
    @Transactional(readOnly = false)
    public BaseResult save(TbUser tbUser) {

        String validator = BeanValidator.validator(tbUser);

        //检查邮箱是否被注册
        TbUser checkEmail = dao.getByEmail(tbUser.getEmail());
        if (checkEmail != null){
            return BaseResult.fail(500,"邮箱地址已注册！");
        }

        //验证不通过
        if (validator != null){
            return BaseResult.fail(validator);
        }


        //验证通过
        else{
            tbUser.setUpdated(new Date());

            //新增用户
            if (tbUser.getId() == null){
                //密码需要加密处理
                tbUser.setPassword(DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes()));
                tbUser.setCreated(new Date());
                dao.insert(tbUser);
            }
            //编辑用户
            else {
                tbUser.setPassword(DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes()));
                update(tbUser);
            }
        }

        return BaseResult.success("保存用户信息成功！");
    }

    @Override
    public TbUser login(String email, String password) {
        TbUser tbUser = dao.getByEmail(email);
        if (tbUser != null){
            //明文密码加密
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            //判断明文密码与数据库密码是否一致
            if (md5Password.equals(tbUser.getPassword())){
                return tbUser;
            }
        }
        return null;
    }



}
